module.exports = function(data,args){
    data = data || [],args = args || {};
    function forEach(query,fn,args){
        query = query || {},args = args || {};
        for(var i = 0; i < data.length; i ++){
            var isQuery = true;
            for(var k in query) {
                if(/_|pageSize|pageNum/.test(k)) continue;
                if(data[i] === undefined || query[k] != data[i][k]) isQuery = false;
            }
            if(isQuery) {
                fn(data[i],i);
                if(args.findOne) break;
            }
        }
    }
    this.find = function(query,fn,args){
        args = args || {};
        var rc = [];
        var index = 0;
        forEach(query,function(res,i){
            res._id = i;
            res.index = index;
            index ++;
            rc.push(args.filter ? args.filter(res) : a.clone(res,args.cloneType));
        },args)
        if(args.sortFn) rc.sort(args.sortFn);
        if(args.pageNum){
            var pageSize = args.pageSize || 10,pageNum = args.pageNum || 1,min = pageSize * (pageNum - 1),max = pageNum * pageSize - 1,rows = [];
            for(var i = 0; i < rc.length; i ++) if(i >= min && i <= max) rows.push(rc[i]);
            if(typeof fn == 'function'){
                fn({pageSize:pageSize,pageNum:pageNum,rows:rows,total:rc.length});
            }else{
                return {pageSize:pageSize,pageNum:pageNum,rows:rows,total:rc.length};
            }
        }else{
            if(typeof fn == 'function'){
                fn(rc);
            }else{
                return rc;
            }
        }
    }
    this.insert = function(_data,fn){
        _data = _data || {};
        data.push(_data);
    }
    this.update = function(query,_data,fn,args){
        _data = _data || {};
        var isOk = false;
        forEach(query,function(res,i){
            for(var k in _data){
                res[k] = _data[k];
            }
            data[i] = res;
            isOk = true;
        },args)
        if(typeof fn == 'function'){
            fn(isOk);
        }else{
            return isOk;
        }
    }
    this.remove = function(query,fn,args){
        var isOk = false;
        forEach(query,function(res,i){
            data[i] = undefined;
            isOk = true;
        },args)
        if(typeof fn == 'function'){
            fn(isOk);
        }else{
            return isOk;
        }
    }
}